package devops.katas.integrationtestingwithtestcontainers;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class IntegrationtestingwithtestcontainersApplication {

	public static void main(String[] args) {
		SpringApplication.run(IntegrationtestingwithtestcontainersApplication.class, args);
	}

	@Bean
	public CommandLineRunner commandLineRunner(CustomerRepository customerRepository) {
		return args -> {
			customerRepository.deleteAllInBatch();
			ArrayList<Customer> customers = new ArrayList<>();
			customers.add(createCustomer("First1", "Last1"));
			customers.add(createCustomer("First2", "Last2"));
			customers.add(createCustomer("First3", "Last3"));
			customers.add(createCustomer("First4", "Last4"));
			customers.add(createCustomer("First5", "Last5"));
			customers.add(createCustomer("First6", "Last6"));
			customerRepository.saveAll(customers);
		};
	}

	private Customer createCustomer(String firstName, String lastName) {
		Customer customer = new Customer();
		customer.setFirstName(firstName);
		customer.setLastName(lastName);
		return customer;
	}

}

@Repository
interface CustomerRepository extends JpaRepository<Customer, Long> {
}

@RestController
@AllArgsConstructor
class UserController {
	private CustomerRepository customerRepository;

	@GetMapping("/customers")
	public List<Customer> getCustomers() {
		return customerRepository.findAll();
	}
}

@Data
@Entity
class Customer {
	@Id
	@GeneratedValue
	private Long id;
	private String firstName;
	private String lastName;
}